import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:oral_cloud/config/app_config.dart';
import 'package:oral_cloud/config/constant.dart';
import 'package:oral_cloud/config/resource_mananger.dart';

class Utils {
  static String getImagePath(String name,{String format:"png"}) {
    return "assets/images/$name.$format";
  }
}





///自定义输入框 支持设置最长输入长度 支持获取验证码 密码掩码输入 支持设置键盘类型 支持placeholder
class  MyTextField extends StatefulWidget {
  const MyTextField({
    Key key,
    @required this.controller,
    this.maxLength: 20,
    this.autoFocus: false,
    this.keyboardType: TextInputType.text,
    this.focusNode,
    this.placeHolder,
    this.isInputPwd: false,
    this.getVCode,
    this.countdown: 60, this.enableClick:true, this.prefixIcon, this.prefixIconConstraints, this.contentPaddingV:10, this.fontSize,
  }) : super(key: key);

  final TextEditingController controller;
  final Widget prefixIcon;
  final BoxConstraints prefixIconConstraints;
  final int maxLength;
  final double fontSize;
  final double contentPaddingV;
  final bool autoFocus; //是否自动获得焦点 比如进入搜索页面 一进页面就调起键盘
  final TextInputType keyboardType;
  final FocusNode focusNode; //焦点
  final String placeHolder;
  final bool isInputPwd;
  final Function getVCode;
  final bool enableClick;

  /// 倒计时的秒数，默认60秒。
  final int countdown;
  @override
  MyTextFieldState createState() => MyTextFieldState();


}

class MyTextFieldState extends State<MyTextField> {
  static const int statusNormal=0;
  static const int statusLoading=1;
  static const int statusSuccess=2;//获取接口成功，但是倒计时没有结束
  static const int statusRetry=3;
  static const int statusFailed=4;
  int status;
  bool _isShowDelete = true; //是否显示删除
  bool _isShowPwd = false;
  bool _isAvailableGetVCode = true; //是否可以获取验证码，默认为`false`
  String _verifyStr = '获取验证码';


  /// 倒计时的计时器。
  Timer _timer;

  /// 当前倒计时的秒数。
  int _seconds;


  @override
  void dispose() {
    widget.controller.removeListener(_inputLister);
    _cancelTimer();
    _timer=null;
    super.dispose();
  }


  updateStatus(int status){
    this.status=status;
    if(status==statusNormal){
      _verifyStr = '获取验证码';
    }else if(status==statusLoading){
      _verifyStr = '获取中...';
    }else if(status==statusRetry){
      _verifyStr = '重新获取';
    } else if(status==statusFailed){
      _verifyStr = '获取失败';
    }
    setState(() {

    });

  }

  _inputLister(){
    print(" _inputLister");
      setState(() {
        _isShowDelete = widget.controller.text.isEmpty;
      });
  }

  @override
  void initState() {
    super.initState();
    status=statusNormal;
    widget.controller.addListener(_inputLister);
    _seconds = widget.countdown;
  }



  _startTimer() {
    _timer = Timer.periodic(Duration(seconds: 1), (timer) {
      _seconds--;
      _isAvailableGetVCode = false;
      _verifyStr = '已发送(${_seconds}s)';
      print('_verifyStr=$_verifyStr');
      if (_seconds == 0) {
        status=statusRetry;
        _verifyStr = '重新获取';
        _isAvailableGetVCode = true;
        _seconds = widget.countdown;
        _cancelTimer();
      }
      if(!mounted){
        return;
      }
      setState(() {
        print('setState _verifyStr=$_verifyStr');
      });

    });
  }

  /// 取消倒计时的计时器。
  void _cancelTimer() {
    // 计时器（`Timer`）组件的取消（`cancel`）方法，取消计时器。
    _timer?.cancel();
  }


  @override
  Widget build(BuildContext context) {
    return Stack(
      alignment: Alignment.centerRight,
      children: <Widget>[

        Container(
          child: TextField(
            style:TextStyle(fontSize:widget.fontSize),
            controller: widget.controller,
            maxLength: widget.maxLength,
            autofocus: widget.autoFocus,
            keyboardType: widget.keyboardType,
            obscureText: widget.isInputPwd ? !_isShowPwd : false,
            // 数字、手机号限制格式为0到9(白名单)， 密码限制不包含汉字（黑名单）
            inputFormatters: (widget.keyboardType == TextInputType.number ||
                widget.keyboardType == TextInputType.phone)
                ? [WhitelistingTextInputFormatter(RegExp("[0-9]"))]
                : [BlacklistingTextInputFormatter(RegExp("[\u4e00-\u9fa5]"))],
            decoration: InputDecoration(
              prefixIconConstraints: widget.prefixIconConstraints,
              prefixIcon: widget.prefixIcon,
              hintText: widget.placeHolder,
              hintStyle: TextStyle(color: Color(0xFF999999), fontSize: FontSize.fontSizeL),
              contentPadding:  EdgeInsets.symmetric(horizontal:10,vertical: widget.contentPaddingV),
              counterText: '',
              focusedBorder: OutlineInputBorder (
                  borderSide: BorderSide(
                    color: Color(MYColors.borderFocusColor),
                    width: 0.5,
                  )),
              enabledBorder: OutlineInputBorder(
                  borderSide: BorderSide(
                    color: Color(MYColors.borderNormalColor),
                    width: 0.5,
                  )),
            ),
          ),

          ),


        Row(
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
            /**
             * 控制child是否显示
             *
                当offstage为true，控件隐藏； 当offstage为false，显示；
                当Offstage不可见的时候，如果child有动画等，需要手动停掉，Offstage并不会停掉动画等操作。

                const Offstage({ Key key, this.offstage = true, Widget child })
            */
            Offstage(
                offstage: _isShowDelete,
                child: Container(
                  // margin: EdgeInsets.only(right: 16),
                  child: InkWell(
                    highlightColor: Colors.transparent,
                    splashColor: Colors.transparent,
                    child: Icon(CupertinoIcons.clear,
                    size: 30, color: Theme.of(context).hintColor),
                    onTap: () {
                      setState(() {
                        widget.controller.text = "";
                      });
                    },
                  ),
                )),
            Offstage(
              offstage: !widget.isInputPwd,
              child: Container(
                margin: EdgeInsets.only(right: 10),
                child: InkWell(
                  child: Image.asset(
                    _isShowPwd
                        ? ImageHelper.wrapAssets('eye_open.png')
                        : ImageHelper.wrapAssets('eye_closed.png'),
                    width: 18.0,
                    height: 18.0,
                  ),
                  onTap: () {
                    setState(() {
                      _isShowPwd = !_isShowPwd;
                    });
                  },
                ),
              ),
            ),
            Offstage(
                offstage: widget.getVCode == null,
                child: Container(
                    margin: EdgeInsets.only(right: 10),
                    width: ScreenUtil.getInstance().setWidth(AppConfig.vCodeWidgetWidth),
                    height: widget.contentPaddingV+ScreenUtil.getInstance().setHeight(40),
                    decoration: new BoxDecoration(
                        border: new Border.all(
                            color: _isAvailableGetVCode&&widget.enableClick&&(status!=statusLoading&&status!=statusSuccess)
                                ? Color(MYColors.borderFocusColor)
                                : Color(MYColors.btnBgDisabledColor),
                            width: 0.5)),
                    child: FlatButton(
//                      disabledColor: Color(0xFFCCCCCC),
                      onPressed: _seconds == widget.countdown &&widget.enableClick&&status!=statusLoading? () async {
                        updateStatus(statusLoading);
                        bool canGetVCode=await widget.getVCode();
                        print('canGetVCode=$canGetVCode');
                        if(canGetVCode){
                          updateStatus(statusSuccess);
                          _startTimer();
                        }else{
                          updateStatus(statusFailed);
                        }
                      } : null,
                      child: Text(
                        '$_verifyStr',
                        maxLines: 1,
                        style: TextStyle(
                          
                          fontSize: FontSize.fontSizeM,
                          color: _isAvailableGetVCode&&widget.enableClick&&(status!=statusLoading&&status!=statusSuccess)
                              ? Color(MYColors.borderFocusColor)
                              : Color(MYColors.textDisabledColor),
                        ),
                      ),
                    )))
          ],
        )
      ],
    );
  }




}
